using System;
using System.IO;
using System.Threading.Tasks;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;

namespace AvaAI批量点评系统.Services;

public class ImageService
{
    public async Task<string> ConvertImageToBase64Async(string imagePath)
    {
        try
        {
            if (!File.Exists(imagePath))
            {
                throw new FileNotFoundException($"图片文件不存在: {imagePath}");
            }

            // 读取图片并转换为base64
            using var image = await Image.LoadAsync(imagePath);
            
            // 可选：调整图片大小以减少API调用时间
            if (image.Width > 1024 || image.Height > 1024)
            {
                image.Mutate(x => x.Resize(new ResizeOptions
                {
                    Size = new Size(1024, 1024),
                    Mode = ResizeMode.Max
                }));
            }

            using var ms = new MemoryStream();
            
            // 根据文件扩展名选择合适的编码格式
            var extension = Path.GetExtension(imagePath).ToLowerInvariant();
            if (extension == ".png")
            {
                await image.SaveAsync(ms, new PngEncoder());
            }
            else
            {
                await image.SaveAsync(ms, new JpegEncoder { Quality = 85 });
            }

            var imageBytes = ms.ToArray();
            return Convert.ToBase64String(imageBytes);
        }
        catch (Exception ex)
        {
            throw new Exception($"转换图片失败: {ex.Message}");
        }
    }

    public async Task<string> SaveBase64ImageAsync(string base64Image, string fileName)
    {
        try
        {
            var imageBytes = Convert.FromBase64String(base64Image);
            var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            var filePath = Path.Combine(desktopPath, fileName);

            await File.WriteAllBytesAsync(filePath, imageBytes);
            return filePath;
        }
        catch (Exception ex)
        {
            throw new Exception($"保存图片失败: {ex.Message}");
        }
    }

    public bool IsValidImageFile(string filePath)
    {
        if (!File.Exists(filePath))
            return false;

        var extension = Path.GetExtension(filePath).ToLowerInvariant();
        return extension is ".jpg" or ".jpeg" or ".png" or ".bmp" or ".gif" or ".webp";
    }

    public async Task<(int width, int height, long fileSize)> GetImageInfoAsync(string imagePath)
    {
        try
        {
            using var image = await Image.LoadAsync(imagePath);
            var fileInfo = new FileInfo(imagePath);
            return (image.Width, image.Height, fileInfo.Length);
        }
        catch (Exception ex)
        {
            throw new Exception($"获取图片信息失败: {ex.Message}");
        }
    }
} 